appModule.service("sessionService", ["$ionicPopup", function($ionicPopup) {
    var sshClient = null;
    try {
        sshClient = cordova.require("lee-plugin-sshclient.sshclient")
    } catch (e) {
        $ionicPopup.alert({
            title: '程序初始化失败！' + e
        });
        return true;
    }
    var service = {
        connect: function(sshSession, successCallback, errorCallback) {
            if(! sshClient) {
                errorCallback && errorCallback("程序未初始化...");
            }
            console.info("连接SSH服务器: " + JSON.stringify(sshSession));
            var sshSessionConfig = sshSession.sshSessionConfig;
            sshClient.connect(sshSession.id, sshSessionConfig.host, sshSessionConfig.port, sshSessionConfig.user, sshSessionConfig.password, successCallback, errorCallback);
        },
        execute: function(sshSessionId, command, successCallback, errorCallback) {
            sshClient.execute(sshSessionId, command, successCallback, errorCallback);
        },
        close: function(sshSessionId, successCallback, errorCallback) {
            sshClient.close(sshSessionId, successCallback, errorCallback);
        },

        connectSuccess: function(sshSession, terminalDiv) {
            return function (msg) {
                alert("connectSuccess: " + msg);
                terminalDiv.terminal(function(command, term) {
                    if (command !== '') {
                        try {
                            service.execute(sshSession.id, command, service.executeSuccess);
                            // term.echo(new String(result));
                        } catch(e) {
                            term.error(new String(e));
                        }
                    } else {
                        term.echo('');
                    }
                }, {
                    greetings: '连接到' + sshSession.sshSessionConfig.host + "...",
                    name: sshSession.name,
                    height: '100%',
                    prompt: 'root> '
                });
            };
        },
        connectError: function (msg) {
            $ionicPopup.alert({title: "连接失败: " + msg});
        },

        executeSuccess: function (msg) {
            alert("executeSuccess: " + msg);
        }
    };
    return service;
}]);